package com.undsf.utility;

import java.util.*;

/**
 * Created by Arathi on 2016/10/13.
 */
public class Forest {
    public Map<String, Node> nodes;
    public List<Node> roots;

    public Forest() {
        nodes = new HashMap<String, Node>();
        roots = new ArrayList<Node>();
    }

    public void addNode(Node node) {
        nodes.put(node.key, node);
    }

    public Node getNode(String key) {
        return nodes.get(key);
    }

    public void build() {
        for (Node node : nodes.values()) {
            Node parent = nodes.get(node.parentKey);
            if (parent == null) {
                roots.add(node);
                if (node.parentKey != null) {
                    System.err.println("未找到ID为" + node.parentKey + "的对象");
                }
            }
            else {
                parent.addChild(node);
                node.parent = parent;
            }
        }
    }

    public void getChildren(List<Node> linealList, Node node) {
        if (node == null || node.children == null) return;
        for (Node child : node.children) {
            linealList.add(child);
            getChildren(linealList, child);
        }
    }

    public List<Node> toDfsList() {
        List<Node> linealList = new ArrayList<Node>();
        for (Node root : roots) {
            getChildren(linealList, root);
        }
        return linealList;
    }
}
